package cn.codergege.demoapp.dao

import groovy.sql.Sql
import groovy.text.SimpleTemplateEngine as STE

import org.apache.commons.dbcp2.BasicDataSource

@groovy.util.logging.Slf4j
class DbHelper {

	Sql db

	DbHelper() {
		def ds = new BasicDataSource()
		ds.with {
			driverClassName = 'com.mysql.cj.jdbc.Driver'
			username = 'root'
			password = 'root'
			url = 'jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=false'
		}
		db = new Sql(ds)
	}

	def createTableTemplate = new STE().createTemplate('''
drop table $tableName if exists;
create table $tableName(
id int primary key auto_increment,
$fields
)engine innodb default charset utf8;
''')

	def executeDdl(DataAccessObject dao) {
		def template = createTableTemplate;
		def binding = [
			tableName: dao.tableName,
			//fields:
		]
		def ddl = template.make(binding).toString()
		db.execute ddl
	}
}
